package cn.jsu.oj.dispatchServer.satellite.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类型工具
 *
 * @author shan
 * @date 2022/07/07
 */
public class TypeUtil {

    /**
     * obj转map
     *
     * @param obj   obj
     * @param key   键
     * @param value 值
     * @return {@link Map }<{@link K }, {@link V }>
     */
    public static <K, V> Map<K, V> objToMap(Object obj, Class<K> key, Class<V> value) {
        HashMap<K, V> result = new HashMap<>();
        if (obj instanceof Map<?, ?>) {
            Map<?, ?> map = (Map<?, ?>) (obj);
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                result.put(key.cast(entry.getKey()), value.cast(entry.getValue()));
            }
        }
        return result;
    }

    /**
     * obj转list
     *
     * @param obj     obj
     * @param element 元素
     * @return {@link List }<{@link T }>
     */
    public static <T> List<T> objToList(Object obj, Class<T> element) {
        List<T> list = new ArrayList<>();
        if (obj instanceof List<?>) {
            for (Object o : (List<?>) obj) {
                list.add(element.cast(o));
            }
        }
        return list;
    }
}
